import os
from fastapi import FastAPI
from dotenv import load_dotenv
from tortoise.contrib.fastapi import register_tortoise
from .import settings
from .apps.common.views import app as common_app
from .apps.users.views import app as users_app
from .apps.chat.views import app as chat_app
from .apps.wxpay.views import app as wxpay_app
from .apps.upload.views import app as upload_app
from .utils import middleware, exceptions, redis_tools

def create_app() -> FastAPI:
    """工厂函数，创建应用实例"""
    # 加载.env文件中的环境变量
    load_dotenv()
    app: FastAPI = FastAPI(
        title=os.environ.get('APP_NAME'),
        summary=os.environ.get('APP_SUMMARY'),
        description=os.environ.get('APP_DESCRIPTION'),
        version=os.environ.get('APP_VERSION'),
        # # 注册全局异常处理函数
        exception_handlers={
            exceptions.HTTPException: exceptions.global_http_exception_handler,
            exceptions.RequestValidationError: exceptions.global_request_exception_handler,
        }
    )

    # 把Tortoise-orm注册到App应用对象中
    # register_tortoise(
    #     app,
    #     config=settings.TORTOISE_ORM,
    #     generate_schemas=False,  # 是否自动生成表结构
    #     add_exception_handlers=True,  # 是否启用自动异常处理
    # )
    # redis连接对象注册到App应用对象中
    # redis_tools.register_redis(
    #     app,
    #     config=settings.REDIS,
    # )
    # 注册通用路由
    # app.include_router(common_app, tags=['公共模块'])
    # app.include_router(users_app, prefix='/users', tags=['用户模块'])
    # app.include_router(chat_app, prefix='/chat', tags=['chat模块'])
    # app.include_router(wxpay_app, prefix='/api/wxpay', tags=['微信支付模块'])
    app.include_router(upload_app, prefix='/api', tags=['上传模块'])
    # 注册中间件函数
    http_middleware = app.middleware('http')
    http_middleware(middleware.log_requests)
    return app